﻿/******************************************************************************
 *  Author：       Commscope ITDC Suzhou Web Team 
 *  CreateDate：   21/02/2012 2:27:00 PM
 *
 *
 ******************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;

namespace EasyDLL.Net
{
    /// <summary>
    /// http请求封装
    /// </summary>
    public class HttpWrapper
    {
        #region - 事件 -

        public delegate void GetHtmlAsycDelegate(Stream responseStream, string identity);
        /// <summary>
        /// GetHtmlStringAsyc异步调用完成时触发
        /// </summary>
        public event GetHtmlAsycDelegate GetHtmlAsycComplete;
        /// <summary>
        /// GetHtmlStringAsyc异步调用完成时触发
        /// </summary>
        public void OnGetHtmlAsycComplete(Stream responseStream, string identity)
        {
            GetHtmlAsycDelegate handler = GetHtmlAsycComplete;
            if (handler != null)
            {
                handler(responseStream, identity);
            }
        }

        #endregion

        /// <summary>
        /// 获得基础流
        /// </summary>
        /// <param name="uri">网址</param>
        /// <param name="cc">cookie容器，可以为NULL</param>
        /// <returns></returns>
        public Stream GetBaseStream(string uri, CookieContainer cc)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);   //用指定Uri创建一个request
                if (cc != null)
                {
                    request.CookieContainer = cc;
                }
                //浏览器欺骗
                request.ContentType = "application/x-www-form-urlencoded";
                request.Accept = @"application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
                request.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.9 Safari/533.2 ChromePlus/1.3.9.0";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();      //根据创建的request得到响应response
                Stream responseStream = response.GetResponseStream();  //创建一个流来获得响应体
                return responseStream;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 获得网页
        /// </summary>
        /// <param name="uri">网址</param>
        /// <param name="postData"></param>
        /// <param name="cc">cookie容器，可以为null</param>
        /// <param name="encoding">网页编码</param>
        /// <returns></returns>
        public string GetHtmlString(string uri, string postData, CookieContainer cc, Encoding encoding)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                request.ContentType = "application/x-www-form-urlencoded";
                request.AllowAutoRedirect = true;
                request.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
                request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.9 Safari/533.2 ChromePlus/1.3.9.0";
                request.CookieContainer = cc;     //设置request产生cookie的容器
                if (postData != null)
                {
                    request.Method = "Post";
                    byte[] byterequest = Encoding.UTF8.GetBytes(postData);
                    request.ContentLength = byterequest.Length;
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(byterequest, 0, byterequest.Length);
                    }
                }

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responsestream = response.GetResponseStream())
                    {
                        if (responsestream != null)
                        {
                            StreamReader sr = new StreamReader(responsestream, encoding);
                            string html = sr.ReadToEnd();
                            return html;
                        }
                        return string.Empty;
                    }
                }
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 异步获得网页，请在调用此方法之前
        /// 实现GetHtmlAsycComplete事件来处理完成事件
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="identity">用于标记此次异步的标志，在GetHtmlAsycComplete事件的参数中能够得到这个值</param>
        public void GetHtmlStringAsyc(string uri, string identity)
        {
            WebRequest request = WebRequest.Create(uri);
            request.Timeout = 5000;
            request.BeginGetResponse(OnResponse, new object[] { identity, request });
        }

        private void OnResponse(IAsyncResult ar)
        {
            object[] objArgs = ar.AsyncState as object[];
            if (objArgs != null)
            {
                HttpWebRequest request = (HttpWebRequest)objArgs[1];
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar);
                Stream stream = response.GetResponseStream();
                OnGetHtmlAsycComplete(stream, objArgs[0].ToString());
            }
        }

        /// <summary>
        /// 中文url编码
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public string UrlEncode(string buffer)
        {
            byte[] bty = Encoding.Default.GetBytes(buffer);
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < bty.Length; i++)
            {
                builder.Append("%");
                builder.Append(bty[i].ToString("x2"));
            }
            return builder.ToString();
        }
    }
}
